import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  Modal,
  Badge,
  Divider,
  Steps,
  TreeSelect,
  Upload,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './GoodsList.less';
import goods from '../../models/goods';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'success'];
const status = ['下架', '上架'];

@connect(({ goods, loading }) => ({
  goods,
  loading: loading.models.goods,
}))
@Form.create()
class CreateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      formVals: {
        crowd_id: [],
        show_title: [],
        name: [],
        producing_area: [],
        unit: [],
        slogan: [],
        img_url: [],
        illustrate: [],
        now_price: [],
        out_price: [],
        in_price: [],
        status: [],
        c_id: [],
        b_id: [],
      },
      small_image: [],
      illustrate: [],
      img_url: [],
      cData: [],
      currentStep: 0,
      previewVisible: false,
      previewImage: '',
    };
    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  handleNext = currentStep => {
    const { form, handleAdd } = this.props;
    const { formVals: oldValue, small_image, illustrate, img_url } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = { ...oldValue, ...fieldsValue, small_image, illustrate, img_url };
      this.setState(
        {
          formVals,
        },
        () => {
          if (currentStep < 4) {
            this.forward();
          } else {
            this.setState({
              currentStep: 0,
              formVals: {},
            });
            handleAdd(formVals);
          }
        }
      );
    });
  };

  backward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep - 1,
    });
  };

  forward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep + 1,
    });
  };

  smallImageGetBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  smallImageList = info => {
    this.setState({ small_image: info.fileList });
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }

    if (info.file.status === 'done') {
      const small_image_data = [
        {
          uid: info.file.uid,
          url: info.file.response.data.img_path,
          name: info.file.response.data.img_path,
          status: 'done',
        },
      ];
      this.smallImageGetBase64(info.file.originFileObj, () =>
        this.setState({
          small_image: small_image_data,
          loading: false,
        })
      );
    }
  };

  illustrateImageList = info => {
    this.setState({ illustrate: info.fileList });
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }

    if (info.file.status === 'done') {
      info.fileList.map(function(item) {
        if (item.response) {
          item.url = item.response.data.img_path;
        }
      });
      this.smallImageGetBase64(info.file.originFileObj, () =>
        this.setState({
          illustrate: info.fileList,
          loading: false,
        })
      );
    }
  };

  imgUrlImageList = info => {
    this.setState({ img_url: info.fileList });
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }

    if (info.file.status === 'done') {
      info.fileList.map(function(item, k) {
        info.fileList[k].url = item.response.data.img_path;
      });
      this.smallImageGetBase64(info.file.originFileObj, () =>
        this.setState({
          img_url: info.fileList,
          loading: false,
        })
      );
    }
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  renderContent = (currentStep, formVals) => {
    const { form } = this.props;
    const {
      goods: { treeData, data, brand_data },
    } = this.props;
    const { previewVisible, previewImage, small_image, illustrate, img_url } = this.state;
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    if (currentStep === 1) {
      return [
        <FormItem key="small_image" {...this.formLayout} label="商品列表图">
          {form.getFieldDecorator('small_image', {
            // rules:[{
            //                         //     required:true,message:'请上传图片'
            //                         // }]
          })(
            <div>
              <Upload
                name="img"
                action="/api/api/0.0.1/tool/upload/img"
                listType="picture-card"
                fileList={small_image}
                onPreview={this.handlePreview}
                onChange={this.smallImageList}
              >
                {small_image.length < 1 ? uploadButton : null}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </div>
          )}
        </FormItem>,

        <FormItem key="unit" {...this.formLayout} label="规格">
          {form.getFieldDecorator('unit', {
            rules: [{ required: true, message: '请输入规格！' }],
            initialValue: formVals.unit,
          })(<Input placeholder="请输入" />)}
        </FormItem>,

        <FormItem key="c_id" {...this.formLayout} label="分类">
          {form.getFieldDecorator('c_id', {
            rules: [{ required: true, message: '请选择分类！' }],
            initialValue: formVals.c_id,
          })(
            <TreeSelect
              style={{ width: 300 }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={treeData}
              placeholder="请选择一个分类"
              treeDefaultExpandAll
              onChange={this.onChange}
            />
          )}
        </FormItem>,

        <FormItem key="b_id" {...this.formLayout} label="品牌">
          {form.getFieldDecorator('b_id', {
            rules: [{ required: true, message: '请选择品牌！' }],
            initialValue: formVals.b_id,
          })(
            <Select style={{ width: '100%' }}>
              {brand_data.map(function(item) {
                return (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                );
              })}
            </Select>
          )}
        </FormItem>,

        <FormItem key="illustrate" {...this.formLayout} label="详细介绍">
          {form.getFieldDecorator('illustrate', {
            rules: [{ required: true, message: '请输入介绍' }],
            initialValue: formVals.illustrate,
          })(<TextArea rows={4} placeholder="请输入至少15个字" />)}
        </FormItem>,
      ];
    }
    if (currentStep === 2) {
      return [
        <FormItem key="now_price" {...this.formLayout} label="现价">
          {form.getFieldDecorator('now_price', {
            rules: [
              {
                required: true,
                message: '请输入现价（必须是数字）！',
                whitespace: true,
                pattern: new RegExp(/^[1-9]\d*$/, 'g'),
              },
            ],
            initialValue: formVals.now_price,
          })(<Input placeholder="请输入" />)}
        </FormItem>,
        <FormItem key="out_price" {...this.formLayout} label="售价">
          {form.getFieldDecorator('out_price', {
            rules: [
              {
                required: true,
                message: '请输入售价（必须是数字）！',
                whitespace: true,
                pattern: new RegExp(/^[1-9]\d*$/, 'g'),
              },
            ],
            initialValue: formVals.out_price,
          })(<Input placeholder="请输入" />)}
        </FormItem>,
        <FormItem key="in_price" {...this.formLayout} label="进价">
          {form.getFieldDecorator('in_price', {
            rules: [
              {
                required: true,
                message: '请输入进价（必须是数字）！',
                whitespace: true,
                pattern: new RegExp(/^[1-9]\d*$/, 'g'),
              },
            ],
            initialValue: formVals.in_price,
          })(<Input placeholder="请输入" />)}
        </FormItem>,
      ];
    }
    if (currentStep === 3) {
      return [
        <FormItem key="img_url" {...this.formLayout} label="商品轮播图">
          {form.getFieldDecorator('img_url', {
            initialValue: formVals.img_url,
          })(
            <div>
              <Upload
                name="img"
                action="/api/api/0.0.1/tool/upload/img"
                listType="picture-card"
                fileList={img_url}
                onPreview={this.handlePreview}
                onChange={this.imgUrlImageList}
              >
                {img_url.length >= 3 ? null : uploadButton}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </div>
          )}
        </FormItem>,
      ];
    }
    if (currentStep === 4) {
      return [
        <FormItem key="illustrate" {...this.formLayout} label="商品插图">
          {form.getFieldDecorator('illustrate', {
            initialValue: formVals.img_url,
          })(
            <div>
              <Upload
                name="img"
                action="/api/api/0.0.1/tool/upload/img"
                listType="picture-card"
                fileList={illustrate}
                onPreview={this.handlePreview}
                onChange={this.illustrateImageList}
              >
                {illustrate.length >= 3 ? null : uploadButton}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </div>
          )}
        </FormItem>,
        <FormItem key="status" {...this.formLayout} label="是否上架">
          {form.getFieldDecorator('status', {
            initialValue: formVals.status,
          })(
            <Select style={{ width: '100%' }}>
              <Option value="0">下架</Option>
              <Option value="1">上架</Option>
            </Select>
          )}
        </FormItem>,
      ];
    }
    return [
      <FormItem key="crowd_id" {...this.formLayout} label="商品所属群">
        {form.getFieldDecorator('crowd_id', {
          rules: [{ required: true, message: '请选择！' }],
          initialValue: formVals.crowd_id,
        })(
          <Select style={{ width: '100%' }}>
            {data.map(function(item) {
              return (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        )}
      </FormItem>,
      <FormItem key="show_title" {...this.formLayout} label="标题">
        {form.getFieldDecorator('show_title', {
          rules: [{ required: true, message: '请输入标题！', whitespace: true }],
          initialValue: formVals.show_title,
        })(<Input placeholder="请输入" />)}
      </FormItem>,
      <FormItem key="name" {...this.formLayout} label="商品名称">
        {form.getFieldDecorator('name', {
          rules: [{ required: true, message: '请输入标题！', whitespace: true }],
          initialValue: formVals.name,
        })(<Input placeholder="请输入" />)}
      </FormItem>,
      <FormItem key="producing_area" {...this.formLayout} label="产地">
        {form.getFieldDecorator('producing_area', {
          rules: [{ required: true, message: '请输入产地！', whitespace: true }],
          initialValue: formVals.producing_area,
        })(<Input placeholder="请输入" />)}
      </FormItem>,
      <FormItem key="slogan" {...this.formLayout} label="广告语">
        {form.getFieldDecorator('slogan', {
          rules: [
            { required: true, message: '请输入至少15个字的广告语！', min: 15, whitespace: true },
          ],
          initialValue: formVals.slogan,
        })(<TextArea rows={4} placeholder="请输入至少15个字" />)}
      </FormItem>,
    ];
  };

  renderFooter = currentStep => {
    const { handleModalVisible } = this.props;
    if (currentStep === 1) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleModalVisible()}>
          取消
        </Button>,
        <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 2) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleModalVisible()}>
          取消
        </Button>,
        <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 3) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleModalVisible()}>
          取消
        </Button>,
        <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 4) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleModalVisible()}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)}>
          完成
        </Button>,
      ];
    }
    return [
      <Button key="cancel" onClick={() => handleModalVisible()}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
        下一步
      </Button>,
    ];
  };

  render() {
    const { modalVisible, form, handleAdd, handleModalVisible } = this.props;
    const okHandle = () => {
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        form.resetFields();
        handleAdd(fieldsValue);
      });
    };
    const { currentStep, formVals } = this.state;
    return (
      <Modal
        width={900}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="添加商品"
        visible={modalVisible}
        footer={this.renderFooter(currentStep)}
        onOk={okHandle}
        onCancel={() => handleModalVisible()}
      >
        <Steps style={{ marginBottom: 28 }} size="small" current={currentStep}>
          <Step title="商品简介" />
          <Step title="商品规格" />
          <Step title="商品价格" />
          <Step title="商品轮播图" />
          <Step title="商品商插图" />
        </Steps>
        {this.renderContent(currentStep, formVals)}
      </Modal>
    );
  }
}

@connect(({ goods, loading }) => ({
  goods,
  loading: loading.models.goods,
}))
@Form.create()
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      formVals: {
        key: props.values.key,
        show_title: props.values.show_title,
        name: props.values.name,
        producing_area: props.values.producing_area,
        unit: props.values.unit,
        slogan: props.values.slogan,
        illustrate: props.values.illustrate,
        now_price: props.values.now_price,
        out_price: props.values.out_price,
        in_price: props.values.in_price,
        salenum: props.values.salenum,
        status: props.values.status,
        c_id: props.values.c_id,
        b_id: props.values.b_id,
        on_off_time: props.on_off_time,
        img_url: props.values.img_url,
        small_image: props.values.small_image,
        inventory: props.values.inventory,
      },
      currentStep: 0,

      small_image: props.values.small_image ? props.values.small_image : [],
      illustrate: props.values.illustrate ? props.values.illustrate : [],
      img_url: props.values.img_url ? props.values.img_url : [],

      previewVisible: false,
      previewImage: '',
    };

    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  handleNext = currentStep => {
    const { form, handleUpdate } = this.props;
    const { formVals: oldValue, small_image, illustrate, img_url } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = { ...oldValue, ...fieldsValue, small_image, illustrate, img_url };
      this.setState(
        {
          formVals,
        },
        () => {
          if (currentStep < 4) {
            this.forward();
          } else {
            handleUpdate(formVals);
          }
        }
      );
    });
  };

  backward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep - 1,
    });
  };

  forward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep + 1,
    });
  };

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  smallImageGetBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  smallImageList = info => {
    this.setState({ small_image: info.fileList });
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }

    if (info.file.status === 'done') {
      const small_image_data = [
        {
          uid: info.file.uid,
          url: info.file.response.data.img_path,
          name: info.file.response.data.img_path,
          status: 'done',
        },
      ];
      this.smallImageGetBase64(info.file.originFileObj, () =>
        this.setState({
          small_image: small_image_data,
          loading: false,
        })
      );
    }
  };

  illustrateImageList = info => {
    this.setState({ illustrate: info.fileList });
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }

    if (info.file.status === 'done') {
      info.fileList.map(function(item) {
        if (item.response) {
          item.url = item.response.data.img_path;
        }
      });
      this.smallImageGetBase64(info.file.originFileObj, () =>
        this.setState({
          illustrate: info.fileList,
          loading: false,
        })
      );
    }
  };

  imgUrlImageList = info => {
    this.setState({ img_url: info.fileList });
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }

    if (info.file.status === 'done') {
      info.fileList.map(function(item) {
        if (item.response) {
          item.url = item.response.data.img_path;
        }
      });
      this.smallImageGetBase64(info.file.originFileObj, () =>
        this.setState({
          img_url: info.fileList,
          loading: false,
        })
      );
    }
  };

  handleCancel = () => this.setState({ previewVisible: false });

  renderContent = (currentStep, formVals) => {
    const {
      form,
      goods: { treeData, brand_data },
    } = this.props;
    const { previewVisible, previewImage, small_image, illustrate, img_url } = this.state;
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    if (currentStep === 1) {
      return [
        <FormItem key="unit" {...this.formLayout} label="规格">
          {form.getFieldDecorator('unit', {
            rules: [{ required: true, message: '请输入规格！' }],
            initialValue: formVals.unit,
          })(<Input placeholder="请输入" />)}
        </FormItem>,

        <FormItem key="c_id" {...this.formLayout} label="分类">
          {form.getFieldDecorator('c_id', {
            rules: [{ required: true, message: '请选择分类！' }],
            initialValue: formVals.c_id,
          })(
            <TreeSelect
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={treeData}
              placeholder="请选择一个分类"
              treeDefaultExpandAll
              onChange={this.onChange}
            />
          )}
        </FormItem>,

        <FormItem key="b_id" {...this.formLayout} label="品牌">
          {form.getFieldDecorator('b_id', {
            rules: [{ required: true, message: '请选择品牌！' }],
            initialValue: formVals.b_id,
          })(
            <Select style={{ width: '100%' }}>
              {brand_data.map(function(item) {
                return (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                );
              })}
            </Select>
          )}
        </FormItem>,

        <FormItem key="inventory" {...this.formLayout} label="库存">
          {form.getFieldDecorator('inventory', {
            rules: [{ required: true, message: '请输入库存！' }],
            initialValue: formVals.inventory,
          })(<Input placeholder="请输入" />)}
        </FormItem>,

        <FormItem key="small_image" {...this.formLayout} label="商品列表图">
          {form.getFieldDecorator('small_image', {
            rules: [{ required: true, message: '请上传商品列表图！' }],
            initialValue: formVals.small_image,
          })(
            <div>
              <Upload
                name="img"
                action="/api/api/0.0.1/tool/upload/img"
                listType="picture-card"
                fileList={small_image}
                onPreview={this.handlePreview}
                onChange={this.smallImageList}
              >
                {small_image.length < 1 ? uploadButton : null}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </div>
          )}
        </FormItem>,
      ];
    }
    if (currentStep === 2) {
      return [
        <FormItem key="now_price" {...this.formLayout} label="现价">
          {form.getFieldDecorator('now_price', {
            rules: [{ required: true, message: '请输入规格！' }],
            initialValue: formVals.now_price,
          })(<Input placeholder="请输入" />)}
        </FormItem>,
        <FormItem key="out_price" {...this.formLayout} label="售价">
          {form.getFieldDecorator('out_price', {
            rules: [{ required: true, message: '请输入规格！' }],
            initialValue: formVals.out_price,
          })(<Input placeholder="请输入" />)}
        </FormItem>,
        <FormItem key="in_price" {...this.formLayout} label="进价">
          {form.getFieldDecorator('in_price', {
            rules: [{ required: true, message: '请输入规格！' }],
            initialValue: formVals.in_price,
          })(<Input placeholder="请输入" />)}
        </FormItem>,
      ];
    }
    if (currentStep === 3) {
      return [
        <FormItem key="img_url" {...this.formLayout} label="商品轮播图">
          {form.getFieldDecorator('img_url', {
            initialValue: formVals.img_url,
            rules: [{ required: true, message: '请上传商品轮播图！' }],
          })(
            <div>
              <Upload
                name="img"
                action="/api/api/0.0.1/tool/upload/img"
                listType="picture-card"
                fileList={img_url}
                onPreview={this.handlePreview}
                onChange={this.imgUrlImageList}
              >
                {img_url.length >= 3 ? null : uploadButton}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </div>
          )}
        </FormItem>,
      ];
    }
    if (currentStep === 4) {
      return [
        <FormItem key="illustrate" {...this.formLayout} label="商品插图">
          {form.getFieldDecorator('illustrate', {
            initialValue: formVals.img_url,
            rules: [{ required: true, message: '请上传商品插图！' }],
          })(
            <div>
              <Upload
                name="img"
                action="/api/api/0.0.1/tool/upload/img"
                listType="picture-card"
                fileList={illustrate}
                onPreview={this.handlePreview}
                onChange={this.illustrateImageList}
              >
                {illustrate.length >= 3 ? null : uploadButton}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </div>
          )}
        </FormItem>,
        <FormItem key="status" {...this.formLayout} label="是否上架">
          {form.getFieldDecorator('status', {
            initialValue: formVals.status,
            rules: [{ required: true, message: '请选择是否上架！' }],
          })(
            <Select style={{ width: '100%' }}>
              <Option value={0}>下架</Option>
              <Option value={1}>上架</Option>
            </Select>
          )}
        </FormItem>,
      ];
    }
    return [
      <FormItem key="key">
        {form.getFieldDecorator('key', {
          initialValue: formVals.key,
        })(<Input type="hidden" placeholder="请输入" />)}
      </FormItem>,
      <FormItem key="show_title" {...this.formLayout} label="标题">
        {form.getFieldDecorator('show_title', {
          rules: [{ required: true, message: '请输入标题！' }],
          initialValue: formVals.show_title,
        })(<Input placeholder="请输入" />)}
      </FormItem>,
      <FormItem key="name" {...this.formLayout} label="商品名称">
        {form.getFieldDecorator('name', {
          rules: [{ required: true, message: '请输入标题！' }],
          initialValue: formVals.name,
        })(<Input placeholder="请输入" />)}
      </FormItem>,
      <FormItem key="producing_area" {...this.formLayout} label="产地">
        {form.getFieldDecorator('producing_area', {
          rules: [{ required: true, message: '请输入产地！' }],
          initialValue: formVals.producing_area,
        })(<Input placeholder="请输入" />)}
      </FormItem>,
      <FormItem key="slogan" {...this.formLayout} label="广告语">
        {form.getFieldDecorator('slogan', {
          rules: [{ required: true, message: '请输入至少15个字的广告语！', min: 15 }],
          initialValue: formVals.slogan,
        })(<TextArea rows={4} placeholder="请输入至少15个字" />)}
      </FormItem>,
    ];
  };

  renderFooter = currentStep => {
    const { handleUpdateModalVisible } = this.props;
    if (currentStep === 1) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
          取消
        </Button>,
        <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 2) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 3) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 4) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)}>
          完成
        </Button>,
      ];
    }
    return [
      <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
        下一步
      </Button>,
    ];
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible } = this.props;
    const { currentStep, formVals } = this.state;

    return (
      <Modal
        width={900}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="商品修改"
        visible={updateModalVisible}
        footer={this.renderFooter(currentStep)}
        onCancel={() => handleUpdateModalVisible()}
      >
        <Steps style={{ marginBottom: 28 }} size="small" current={currentStep}>
          <Step title="商品简介" />
          <Step title="商品规格" />
          <Step title="商品价格" />
          <Step title="商品轮播图" />
          <Step title="商品插图" />
        </Steps>
        {this.renderContent(currentStep, formVals)}
      </Modal>
    );
  }
}

@connect(({ goods, loading }) => ({
  goods,
  loading: loading.models.goods,
}))
@Form.create()
class GoodsList extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
  };

  columns = [
    {
      title: '商品所属群',
      dataIndex: 'crowd_name',
    },
    {
      title: '标题',
      dataIndex: 'show_title',
    },
    {
      title: '商品名称',
      dataIndex: 'name',
    },
    {
      title: '销量',
      dataIndex: 'salenum',
      sorter: true,
      align: 'right',
    },
    {
      title: '是否上架',
      dataIndex: 'status',
      align: 'right',
      filters: [
        {
          text: status[0],
          value: 0,
        },
        {
          text: status[1],
          value: 1,
        },
      ],
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '上架下架时间',
      dataIndex: 'on_off_time',
      align: 'right',
      sorter: true,
    },
    {
      title: '操作',
      align: 'center',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleUpdateModalVisible(true, record)}>
            <Icon type="edit" theme="twoTone" /> 修改
          </a>
          <Divider type="vertical" />
          <a onClick={() => this.rightListdel(record)}>
            <Icon type="delete" theme="twoTone" /> 删除
          </a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'goods/fetchGoodsList',
    });
  }

  rightListdel = e => {
    const { dispatch } = this.props;
    Modal.confirm({
      title: '删除商品',
      content: '确定删除该商品吗？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'goods/gooddel',
          payload: {
            id: e.key,
          },
        });
      },
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'goods/fetchGoodsList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'goods/fetchGoodsList',
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'rule/remove',
          payload: {
            key: selectedRows.map(row => row.key),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'goods/fetchGoodsList',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      stepFormValues: record || {},
    });
  };

  handleAdd = fields => {
    const { dispatch } = this.props;
    let illustrate = [];
    let img_url = [];
    let small_image = '';
    fields.illustrate.map(function(item, k) {
      illustrate[k] = item.url;
    });
    fields.img_url.map(function(item, k) {
      img_url[k] = item.url;
    });
    fields.small_image.map(function(item) {
      small_image = item.url;
    });
    fields.illustrate = illustrate;
    fields.img_url = img_url;
    fields.small_image = small_image;
    console.log(fields);
    dispatch({
      type: 'goods/goodadd',
      payload: fields,
    });
    this.handleModalVisible();
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;
    let illustrate = [];
    let img_url = [];
    let small_image = '';
    fields.illustrate.map(function(item, k) {
      illustrate[k] = item.url;
    });
    fields.img_url.map(function(item, k) {
      img_url[k] = item.url;
    });
    fields.small_image.map(function(item) {
      small_image = item.url;
    });
    fields.illustrate = illustrate;
    fields.img_url = img_url;
    fields.small_image = small_image;
    dispatch({
      type: 'goods/goodremove',
      payload: {
        ...fields,
      },
    });
    this.handleUpdateModalVisible();
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="商品名称">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="是否上架">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">下架</Option>
                  <Option value="1">上架</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="规格">
              {getFieldDecorator('unit')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="标题">
              {getFieldDecorator('show_title')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="产地">
              {getFieldDecorator('producing_area')(<InputNumber style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="商品名称">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>

        <div style={{ overflow: 'hidden' }}>
          <div style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      goods: { list },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, stepFormValues } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
        <Menu.Item key="approval">批量审批</Menu.Item>
      </Menu>
    );

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    return (
      <PageHeaderWrapper title="商品列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新建
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button>批量操作</Button>
                  <Dropdown overlay={menu}>
                    <Button>
                      更多操作 <Icon type="down" />
                    </Button>
                  </Dropdown>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={list}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
        {stepFormValues && Object.keys(stepFormValues).length ? (
          <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={stepFormValues}
          />
        ) : null}
      </PageHeaderWrapper>
    );
  }
}

export default GoodsList;
